import sys
from pathlib import Path
import json
from typing import Optional

sys.path.append(str(Path(__file__).parent.parent.parent))
from reqapi.api import BaseApi, ApiConfig
from model.sms_login_models import SmsSignInRequest, SmsSignInResponse


class AuthSmsLoginApi(BaseApi):
    """短信登录API"""
    
    def sms_sign_in(self, mobile: str, code: str, area: str = "86", raise_on_error: bool = False) -> Optional[SmsSignInResponse]:
        """短信验证码登录，统一风格，异常和错误码返回 None"""
        endpoint = "/api/user/Auth/SmsSignIn"
        url = f"{self.BASE_URL}{endpoint}"
        request = SmsSignInRequest(
            Area=area,
            Code=code,
            DeviceName=f"{ApiConfig.BRAND} {ApiConfig.DEVICE_TYPE}",
            Mobile=mobile,
            Sessionid=self.device_id or ""
        )
        request_data = {
            "Area": request.Area,
            "Code": request.Code,
            "DeviceName": request.DeviceName,
            "Mobile": request.Mobile,
            "Sessionid": request.Sessionid
        }
        headers = self.common_headers.copy()
        headers["apptype"] = "4"
        headers["authorization"] = "Bearer"
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(request_data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=request_data, headers=headers, need_encrypt=False)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                resp_json = response
            elif hasattr(response, 'json'):
                resp_json = response.json()
            else:
                resp_json = response
            print(f"响应内容: {json.dumps(resp_json, indent=2, ensure_ascii=False)}")
            # 兼容code/Code
            code_val = resp_json.get('Code', resp_json.get('code', -1))
            if code_val != 0:
                print(f"API返回错误: {resp_json.get('Msg', resp_json.get('msg', '未知错误'))}")
                if raise_on_error:
                    raise Exception(f"业务处理失败: {resp_json.get('Msg', resp_json.get('msg'))}")
                return None
            # 兼容 from_dict 或直接解包
            if hasattr(SmsSignInResponse, 'from_dict'):
                return SmsSignInResponse.from_dict(resp_json)
            return SmsSignInResponse(**resp_json)
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            if raise_on_error:
                raise
            return None


def main():
    """测试短信登录API"""
    try:
        # 使用示例设备ID
        device_id = "Z+Z/Uj4xyKoDAJp249r21qHx"
        
        # 创建API实例
        api = AuthSmsLoginApi(
            device_token=device_id,
            device_id=device_id,
            auth_token="Bearer",  # 根据请求示例设置
            uk="5FGaLrLar6b7EWUnNmqNpKGjU88E7TrsHnqsWlwo9ncsogqazR1hLGldi30biVJ1N"  # 示例UK值
        )
        
        # 发送请求 - 使用示例手机号和验证码
        response = api.sms_sign_in(
            mobile="15999957262",  # 示例手机号，实际使用时替换
            code="312934",  # 示例验证码，实际使用时替换为收到的验证码
            area="86"  # 区号，默认中国
        )
        
        print("\n=== 短信登录结果 ===")
        if response is None:
            print("短信验证码登录失败，可能是登录信息失效或接口返回错误。")
        else:
            print(f"状态码: {response.Code}")
            print(f"消息: {response.Msg}")
            print(f"提示类型: {response.TipType}")
            data = response.Data
            if isinstance(data, dict):
                token = data.get('Token')
                nickname = data.get('NickName')
                is_open_stock = data.get('IsOpenStock')
                is_reg = data.get('IsReg')
                tips = data.get('ForeignAccountTips')
            else:
                token = getattr(data, 'Token', None)
                nickname = getattr(data, 'NickName', None)
                is_open_stock = getattr(data, 'IsOpenStock', None)
                is_reg = getattr(data, 'IsReg', None)
                tips = getattr(data, 'ForeignAccountTips', None)
            print(f"登录令牌: {token}")
            print(f"用户昵称: {nickname}")
            print(f"是否开通库存: {is_open_stock}")
            print(f"是否注册: {is_reg}")
            if tips:
                print(f"外部账号提示: {tips}")
        return token if response and response.Code == 0 else None
        
    except Exception as e:
        print(f"短信登录失败: {e}")
        return None


if __name__ == "__main__":
    main()
